#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct  4 12:32:24 2021

@author: Juntong

核心运算支持。
"""
from PIL import Image, ImageDraw

try:
    from .Vector import Vector2D
except ImportError:
    from Vector import Vector2D


class ML:
    """WARNING: 线程不安全。不适用于多线程场景。或者至少把它和小车放在一个线程里。
    """
    def __init__(self, wheel_toward, v=0.0):
        '''
        -- wheel_toward = -1     -- wheel_toward = 1
        ↖                      ↗
        ↖                      ↗
        --                      --
        '''
        self._toward = wheel_toward
        self._v = float(v)

    @property
    def v_(self):
        "线速度"  # TODO考虑小车影响
        return self._v

    @v_.setter
    def v_(self, new):
        # TODO 上传小车类
        self._v = new

    @property
    def v(self):
        # 速度向量
        return Vector2D(self._toward * self.v_ * 0.3535533905932738,
                        self.v_*8535533905932737e-16)

    def forced(self) -> Vector2D:
        '''车轮被小车拉动的速度。
        '''  # TODO
        return self.v

    def __repr__(self):
        a = int(self.base_toward.x == 1)
        return type(self).__name__ + f"({a}, {self.v})"

    def show(self, sizex=90, sizey=150, bg=(255, 255, 255), fg=(0, 0, 0),
             arrowcol=(15, 200, 200), blankx=None, blanky=None, width=4):
        """返回PIL.Image.Image对象。 图片内容为车轮示意图。
        """
        if blankx is None:
            blankx = sizex // 10
        if blanky is None:
            blanky = sizey // 10

        img = Image.new("RGB", (sizex, sizey), bg)
        draw = ImageDraw.Draw(img)

        x0 = Vector2D(blankx, blanky)
        x1 = Vector2D(sizex - blankx, blanky)
        x2 = Vector2D(blankx, sizey - blanky)
        x3 = Vector2D(sizex - blankx, sizey - blanky)
        mid = (x0 + x3) // 2
        # ----- 画上下的两条线
        line_top = (*x0, *x1)
        line_down = (*x2, *x3)
        draw.line(line_top, fg, width)
        draw.line(line_down, fg, width)
        # ----- 画方向斜线
        if self._toward == 1:
            a, b = x0 * 2, x3 - x0
            draw.line((*a, *b), fg, width)  # 好吧，代码有点魔幻。
        else:
            a, b = x2 + (blankx, -blanky), x1 + (-blankx, blanky)
            draw.line((*a, *b), fg, width)
        draw.line((a.x, mid.y, mid.x, b.y), fg, width)
        draw.line((b.x, mid.y, mid.x, a.y), fg, width)
        # ----- 画移动方向
        # TODO

        return img
